<template>
  <div class="designer-table">
    <div class="desg-table-btn" v-if="addBtn.show">
      <a-button
        type="primary"
        @click="
          () => {
            openModal(addBtn, {});
          }
        "
        >{{ `新增` + (config.modalTitle || "") }}</a-button
      >
    </div>
    <CommonTable
      :data="table.data"
      :columns="table.columns"
      ref="tableRef"
      v-bind="{ ...attrs }"
      @operateChange="operateChange"
      @selectionChange="selectionChange"
      @queryDataChange="queryDataChange"
    ></CommonTable>
  </div>
</template>

<script setup>
const tableRef = ref();
const table = ref({
  data: {
    type: Array | Function,
    default: () => {
      return [];
    },
  },
  columns: [],
});

const addBtn = ref({
  label: "新增",
  class: "table_edit-btn",
  icon: "icon iconfont icon-tianjia",
  key: "add",
  argKey: "id",
  show: true,
});

/**
 * 定义组件的props
 *
 * @param {Object} config - 组件的配置对象
 * @param {Object} config.type - 配置对象的类型，此处为Object
 * @param {Function} config.default - 当config未被传递时的默认值工厂函数
 * @returns {Object} 返回一个包含config属性的对象
 */
const props = defineProps({
  config: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const emit = defineEmits();
const attrs = ref({ ...props.config });
delete attrs.value.data;

/**
 * 打开模态框。
 */
const openModal = (btnInfo, row) => {
  const comm = props.config;
  emit("Table_Modal__Open", comm, btnInfo, row);
};

/**
 * 处理操作变化事件并触发自定义事件。
 *
 * 此函数用于处理表格行的操作变化，并通过emit函数触发一个名为"operateChange"的自定义事件。
 * 事件携带两个参数：操作类型(type)和相关行数据(row)。这个函数使得外部可以监听并响应表格内部的操作变化。
 *
 * @param {string} type - 操作类型。表示对行数据进行的操作，如"编辑"、"删除"等。
 * @param {Object} row - 行数据对象。包含被操作的行的所有数据。
 */
const operateChange = (btnInfo, row) => {
  const comm = props.config;
  emit("Table_Operate__Change", comm, btnInfo, row);
  switch (btnInfo.key) {
    case "create":
    case "edit":
    case "view":
      openModal(btnInfo, row);
      break;
    default:
      break;
  }
};

/**
 * 表格选中变化事件
 *
 */
const selectionChange = (val, row) => {
  emit("Table_Selection__Change", val, row);
};

/**
 * 当查询数据发生变化时调用此函数
 * 该函数通过 emit 触发名为 "queryDataChange" 的自定义事件，并传递变化后的值
 *
 * @param {any} val 变化后的查询数据值
 */
const queryDataChange = (val) => {
  emit("Table_Query_Data__Change", val);
};

const fetchData = () => {
  tableRef.value?.fetchData();
};
const setTable = (val) => {
  let cols = {};
  let dfn = () => {};
  Object.keys({ ...val }).forEach((k) => {
    let n = k.match(/\-[a-zA-Z0-9-_]+$/);
    if (k.startsWith("apiGet")) {
      dfn = val[k];
    }
    if (n) {
      let i = n[0];
      if (!cols[i]) cols[i] = {};
      cols[i][k.replace(/\-[a-zA-Z0-9-_]+$/, "")] = val[k];
    }
  });
  const columns = Object.values(cols);
  const operate = columns.find((a) => a.key === "operate");
  if (operate && props.config.btns && props.config.btns.length) {
    const btcf = {
      edit: {
        label: "编辑",
        class: "table_edit-btn",
        icon: "icon iconfont icon-bianji",
        key: "edit",
        argKey: "roleId",
      },
      delete: {
        label: "删除",
        class: "table_del-btn",
        icon: "icon iconfont icon-shanchu",
        key: "delete",
        content: "请确认是否删除？",
      },
      detail: {
        label: "详情",
        class: "table_edit-btn",
        icon: "icon iconfont icon-xiangqing",
        key: "delete",
        content: "请确认是否删除？",
      },
    };
    props.config.btns.map((a) => {
      if (a === "add") {
        addBtn.value.show = true;
      } else {
        if (!operate.btns) operate.btns = [];
        operate.btns.push(btcf[a]);
      }
    });
  }
  table.value.columns = columns.map((a) => {
    a.dataIndex = a.key;
    return a;
  });
  table.value.data = dfn;
};

watch(
  () => props.config,
  (val) => {
    setTable(val._esr || val);
  },
  {
    deep: true,
    immediate: true,
  },
);

defineExpose({
  fetchData,
});
</script>
<style lang="scss" scoped>
.desg-table-btn {
  padding: 15px 0;
}
</style>
